import * as web3Utils from '@/utils/web3Utils'
import { COOKIE_AUTH_NAME } from '@/utils/contractConfig'
import { setCookie, getCookie } from '@/utils/cookieUtils'

const defaultAccountInfo = {
  long: [],
  short: [],
  longOpenPending: [],
  shortOpenPending: [],
  longClosePending: [],
  shortClosePending: [],
  totalMargin: 0,
  positionMargin: 0,
  unrealizedPnl: 0,
  accountBalance: 0,
  isUsed: false
}

const defaultBoard = {
  // totalLongPositionSize: 0,
  // totalShortPositionSize: 0,
  // totalLongOpenNotional: 0,
  // totalShortOpenNotional: 0,
  // totalUnrealizedPnl: 0,
  maintenanceMarginRatio: 0,
  positionFeeRatio: 0,
  spotPrice: 0,
  marketBalance: 0
}

let addr = getCookie(COOKIE_AUTH_NAME) || ''

const paireOptions = [
  { label: 'BTC/USDT', value: 'BTC/USDT', _marketIdx: 0, instId: 'BTC-USD', token: 'BTC'},
  { label: 'ETH/USDT', value: 'ETH/USDT', _marketIdx: 1, instId: 'ETH-USD', token: 'ETH'}
]

const state = {
  addr: addr.length === 42 && addr.startsWith('0x') ? addr: '',
  account: defaultAccountInfo,
  board: defaultBoard,
  paire: 'ETH/USDT',
  curPaireObj: {},
  paireOptions,
  curPrice: 0, // 展示价格，交易所读取
  candleType: {
    bar: '1m',
    name: '日K',
    label: ''
  },
  candle1D: {
    open: '--',
    close: '--',
    lowest: '--',
    highest: '--'
  },
  curLng: {lng: 'zh'},
  spotPrice: 0, //合约读取，精度8位
  totalMargin: 0, // 合约读取，精度8位
  unrealizedPnl: 0,// 合约读取，精度8位
  positionMargin: 0,// 合约读取，精度8位
}

function updateCurPaireObject(paire) {
  state.curPaireObj = paireOptions.filter(item => item.value === paire)[0]
}

updateCurPaireObject(state.paire)

const mutations = {
  SET_CURLNG:(state, curLng) => {
    state.curLng = curLng
    localStorage.setItem('curLng', JSON.stringify(curLng))
  },
  SET_ADDR: (state, addr) => {
    setCookie(COOKIE_AUTH_NAME, addr)
    state.addr = addr || ''
    // console.log('store/modules/user.js.vue==>>SET_ADDR', '#auth', getCookie(COOKIE_AUTH_NAME), '#addr', state.addr)
  },

  SET_ACCOUNT: (state, account) => {
    state.account = account
  },

  SET_BOARD: (state, board) => {
    state.board = board
  },

  SET_PAIRE: (state, paire) => {
    state.paire = paire
    updateCurPaireObject(paire)
    window._marketIdx = state.curPaireObj._marketIdx
    // console.log('store/modules/user.js.vue==>>SET_PAIRE, state: %o', state)
  },

  SET_CUR_PRICE: (state, price) => {
    state.curPrice = price
  },

  SET_CANDLE_TYPE: (state, candleType) => {
    state.candleType = candleType
  },

  SET_CANDLE_1D: (state, candle1D) => {
    state.candle1D = candle1D
  },

  SET_SPOT_PRICE: (state, spotPrice) => {
    state.spotPrice = spotPrice
  },

  SET_TOTAL_MARGIN: (state, totalMargin) => {
    state.totalMargin = totalMargin
  },
  SET_UnrealizedPnl: (state, unrealizedPnl) => {
    state.unrealizedPnl = unrealizedPnl
  },

  SET_PositionMargin: (state, positionMargin) => {
    state.positionMargin = positionMargin
  },
}



const actions = {
  loginMetamask({ commit, dispatch }, addr) {
    // console.log('store/modules/user.js.vue==>>loginMetamask, addr: %o', addr)
    commit('SET_ADDR', addr)
    commit('SET_ACCOUNT', defaultAccountInfo)
    if (addr) {
      dispatch('updateAccount', addr)
    }
  },

  updateAccount({ commit }, addr) {
    addr = addr || this.getters.addr
    if (addr) {
      web3Utils.getAccount(addr)
        .then(res => {
          // console.log('store/modules/user.js.vue==>>updateAccount.getAccount, res: %o', res)
          commit('SET_ACCOUNT', res)
        })
        .catch(err => {
          // console.log('store/modules/user.js.vue==>>updateAccount.getAccount, err: %o', err)
          commit('SET_ACCOUNT', defaultAccountInfo)
        })
    }
  },

  updateBoard({ commit }) {
    web3Utils.markets()
      .then(res => {
        // console.log('store/modules/user.js.vue==>>updateBoard.markets, res: %o', res)
        commit('SET_BOARD', res)
      })
      .catch(err => {
        // console.log('store/modules/user.js.vue==>>getMarkets, err: %o', err)
      })
  },

  getSpotPrice({commit}){
    web3Utils.getSpotPrice()
      .then(res=>{
        // console.log('store/modules/user.js.vue==>>getSpotPrice, res: %o', res)
        commit('SET_SPOT_PRICE', parseInt(res))
      })
      .catch(err=>{
        // console.log('store/modules/user.js.vue==>>getSpotPrice, err: %o', err)
      })
  },

  getTotalMargin({commit}, addr){
    addr = addr || this.getters.addr
    if(addr) {
      web3Utils.getTotalMargin(addr)
        .then(res=>{
          console.log('store/modules/user.js.vue==>>getTotalMargin, res: %o', res)
          commit('SET_TOTAL_MARGIN', parseInt(res))
        })
        .catch(err=>{
          console.log('store/modules/user.js.vue==>>getTotalMargin, err: %o', err)
        })
    }
  },

  getPositionMargin({commit}, addr){
    addr = addr || this.getters.addr
    if(addr) {
      web3Utils.getPositionMargin(addr)
        .then(res=>{
          console.log('store/modules/user.js.vue==>>getPositionMargin, res: %o', res)
          commit('SET_PositionMargin', parseInt(res))
        })
        .catch(err=>{
          console.log('store/modules/user.js.vue==>>getPositionMargin, err: %o', err)
        })
    }
  },

  getUnrealizedPnl({commit}, addr){
    addr = addr || this.getters.addr
    log('store/modules/user.js.getUnrealizedPnl', {addr})
    if(addr) {
      web3Utils.getUnrealizedPnl(addr)
        .then(res=>{
          console.log('store/modules/user.js.vue==>>getUnrealizedPnl, res: %o', res)
          commit('SET_UnrealizedPnl', parseInt(res))
        })
        .catch(err=>{
          console.log('store/modules/user.js.vue==>>getUnrealizedPnl, err: %o', err)
        })
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
